package com.red.service.impl;

import com.red.mapper.HouseMapper;
import com.red.mapper.OrderMapper;
import com.red.mapper.UserMapper;
import com.red.pojo.Result;
import com.red.pojo.entity.House;
import com.red.pojo.entity.Order;
import com.red.pojo.entity.User;
import com.red.service.IFightService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class FightServiceImpl implements IFightService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HouseMapper houseMapper;

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 抢房
     *
     * @param userId  发起者ID
     * @param houseId 房源ID
     * @return 抢房结果
     */
    @Override
    public Result fight(int userId, int houseId) {
        User user = userMapper.selectUserByID(userId);

        House houses = houseMapper.selectHouseByID(houseId);

        if (houses == null) {
            return Result.error("房源或不存在");
        }

        Order qOrder = new Order();
        qOrder.setHouseId(houseId);
        qOrder.setStatus("0");

        List<Order> orders = orderMapper.selectOrderList(qOrder, 0, 1);

        if (!orders.isEmpty()) {
            Order order = orders.get(0);

            if (order.getUserId() == user.getUserId()) {
                return Result.error("禁止原地TP");
            }
            User competitor = userMapper.selectUserByID(order.getUserId());

            if (competitor.getUserLevel() >= user.getUserLevel()) {
                return Result.error("预定失败");
            } else {
                // 使竞争者的订单失效
                order.setStatus("2");
                orderMapper.updateOrder(order);
            }
        }

        // 插入订单
        Order newOrder = new Order();
        newOrder.setUserId(userId);
        newOrder.setHouseId(houseId);

        if (orderMapper.insertOrder(newOrder) < 1) {
            return Result.error("创建订单失败");
        }

        return Result.success("预定成功");
    }
}
